package com.cwg.dict.ui.rcp.commands.handlers;

import java.util.Iterator;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.handlers.HandlerUtil;

import com.cwg.dict.model.History;
import com.cwg.dict.ui.rcp.Activator;
import com.cwg.dict.ui.rcp.views.HistoryView;

public class MarkFavorite extends AbstractFavoriteHandler {

	@Override
	protected void execute(History h) {
		h.setFavorite(true);
		Activator.getDefault().getHistorical().markFavorite(h.getWord());
	}
}

abstract class AbstractFavoriteHandler extends AbstractHandler {
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().getSelection();
		if (selection != null & selection instanceof IStructuredSelection) {
			IStructuredSelection strucSelection = (IStructuredSelection) selection;
			for (Iterator<History> iterator = strucSelection.iterator(); iterator.hasNext();) {
				execute(iterator.next());
			}
		}

		Activator.getDefault().getHistorical().save();
		getView(event).refresh();
		return null;

	}

	public HistoryView getView(ExecutionEvent event) {
		IWorkbenchPart part = HandlerUtil.getActivePart(event);
		if (part == null) {
			return null;
		}
		return (HistoryView) part;
	}

	abstract protected void execute(History h);
}
